from sqlalchemy import Boolean, Column, Integer, String, Float, Enum, DateTime, ForeignKey
from sqlalchemy.orm import relationship
from .database import Base
import enum
from datetime import datetime
from zoneinfo import ZoneInfo

CHINA_TZ = ZoneInfo("Asia/Shanghai")

class RoomStatus(enum.Enum):
    AVAILABLE = "空闲"
    OCCUPIED = "使用中"
    MAINTENANCE = "维护中"

class User(Base):
    __tablename__ = "users"

    id = Column(Integer, primary_key=True, index=True)
    username = Column(String, unique=True, index=True)
    hashed_password = Column(String)
    is_active = Column(Boolean, default=True)
    theme = Column(String, default="light")

class TimedRoom(Base):
    __tablename__ = "timed_rooms"

    id = Column(Integer, primary_key=True, index=True)
    name = Column(String, unique=True, index=True)
    minimum_charge = Column(Float)  # 最低消费
    minimum_hours = Column(Float)   # 低消时长
    overtime_rate = Column(Float)   # 超时费/小时
    status = Column(String, default=RoomStatus.AVAILABLE.value)  # 包房状态 
    orders = relationship("Order", back_populates="room")

class Category(Base):
    __tablename__ = "categories"

    id = Column(Integer, primary_key=True, index=True)
    name = Column(String, unique=True, index=True)

class Snack(Base):
    __tablename__ = "snacks"

    id = Column(Integer, primary_key=True, index=True)
    name = Column(String, unique=True, index=True)
    price = Column(Float)  # 售价
    cost = Column(Float)   # 成本价
    stock = Column(Integer)  # 库存数量
    unit = Column(String)  # 单位（如：包、瓶、个）
    category_id = Column(Integer, ForeignKey("categories.id"))
    category = relationship("Category")
    description = Column(String, nullable=True)  # 描述
    is_active = Column(Boolean, default=True)  # 是否在售 

class Order(Base):
    __tablename__ = "orders"

    id = Column(Integer, primary_key=True, index=True)
    room_id = Column(Integer, ForeignKey("timed_rooms.id"))
    start_time = Column(DateTime, default=datetime.now(CHINA_TZ))
    end_time = Column(DateTime, nullable=True)
    base_amount = Column(Float, default=0)  # 包房费用
    total_amount = Column(Float, default=0)  # 总费用
    adjustment = Column(Float, default=0)    # 调整金额
    remark = Column(String, nullable=True)   # 备注
    status = Column(String, default="active")  # active, completed
    
    # 关联关系
    room = relationship("TimedRoom", back_populates="orders")
    order_items = relationship("OrderItem", back_populates="order", cascade="all, delete-orphan")

class OrderItem(Base):
    __tablename__ = "order_items"

    id = Column(Integer, primary_key=True, index=True)
    order_id = Column(Integer, ForeignKey("orders.id"))
    snack_id = Column(Integer, ForeignKey("snacks.id"))
    quantity = Column(Integer)
    price = Column(Float)  # 记录购买时的价格
    created_at = Column(DateTime, default=datetime.now(CHINA_TZ))  # 添加时间
    
    # 关联关系
    order = relationship("Order", back_populates="order_items")
    snack = relationship("Snack") 